package controller

import (
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"order_bff/order"
	"order_bff/pkg"
	"strconv"
)

func CreateOrder(c *gin.Context) {
	userId := c.PostForm("user_id")
	userIdInt, _ := strconv.Atoi(userId)
	carId := c.PostForm("car_id")
	carIdInt, _ := strconv.Atoi(carId)
	if len(userId) == 0 || len(carId) == 0 {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "参数不能为空",
			"data": nil,
		})
		return
	}
	comment := pkg.Comment()
	detail, err := comment.CarDetail(context.Background(), &order.CarDetailRequest{CarId: int32(carIdInt)})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "获取车型详情失败",
			"data": nil,
		})
		return
	}
	_, err = comment.CreateOrder(context.Background(), &order.OrderInfoRequest{
		UserId: int32(userIdInt),
		CarId:  int32(carIdInt),
		Price:  detail.Price,
	})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "创建订单失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "创建订单成功",
		"data": nil,
	})
}

func DeleteOrder(c *gin.Context) {
	orderSn := c.PostForm("order_sn")
	if orderSn == "" {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "参数不能为空",
			"data": nil,
		})
		return
	}
	comment := pkg.Comment()
	_, err := comment.DeleteOrder(context.Background(), &order.DeleteOrderRequest{OrderSn: orderSn})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "删除订单失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "删除订单成功",
		"data": nil,
	})
}
